package com.bjpn.settings.controller;

import com.bjpn.settings.bean.User;
import com.bjpn.settings.service.UserService;
import com.bjpn.util.DateToString;
import com.bjpn.util.MessageUtil;
import com.bjpn.util.ReturnObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("toLogin.action")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/loginUser.action")
    @ResponseBody
    public ReturnObject toWorkbenchIndex(String loginCode, String loginPwd, ReturnObject robj,
                                         HttpSession session, HttpServletResponse response){
        User user = userService.getUserByCodeAndPwd(loginCode, loginPwd);
        System.out.println(user);
        //验证账号
        if (user != null) {
            // 验证是否过期
            String currentTime = DateToString.currentTimeToString();
            if (currentTime.compareTo(user.getUserExpireTime()) > 0){
                robj.setMessageCode(MessageUtil.TIME_ERROR_CODE);
                robj.setMessageStr(MessageUtil.TIME_ERROR_MESSAGE);
            // 验证是否被锁定  0表示被锁定
            } else if ("0".equals(user.getUserLockState())) {
                robj.setMessageCode(MessageUtil.LOCK_ERROR_CODE);
                robj.setMessageStr(MessageUtil.LOCK_ERROR_MESSAGE);
            }else {
                session.setAttribute("user", user);
                Cookie c1 = new Cookie("loginCode", loginCode);
                Cookie c2 = new Cookie("loginPwd", loginPwd);
                c1.setPath("/");
                c1.setMaxAge(60*60*24*10);
                c2.setPath("/");
                c2.setMaxAge(60*60*24*10);
                response.addCookie(c1);
                response.addCookie(c2);
                robj.setMessageCode(MessageUtil.LOGIN_SUCCESS_CODE);
                robj.setMessageStr(MessageUtil.LOGIN_SUCCESS_MESSAGE);
            }
        }else {
            robj.setMessageCode(MessageUtil.LOGIN_ERROR_CODE);
            robj.setMessageStr(MessageUtil.LOGIN_ERROR_MESSAGE);
        }
        return robj;
    }

    // 退出登录
    @RequestMapping("/loginOut.action")
    public String loginOut(HttpSession session){
        session.invalidate();
        return "login";
    }
}
